<template>
  <div class="homework-list-container">
    <div class="header-actions">
      <h2>作业管理</h2>
      <el-button type="primary" @click="handleCreateHomework">新建作业</el-button>
    </div>

    <el-table :data="homeworkList" v-loading="loading" border stripe>
      <el-table-column prop="title" label="作业标题" min-width="180" />
      <el-table-column prop="className" label="班级" width="120" />
      <el-table-column prop="subjectName" label="学科" width="120" />
      <el-table-column prop="endTime" label="截止日期" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="submitCount" label="已提交/总人数" width="120">
        <template #default="scope">
          {{ scope.row.submitCount }}/{{ scope.row.studentCount }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleViewHomework(scope.row)"
            link
          >
            查看
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleEditHomework(scope.row)"
            link
          >
            编辑
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleCheckSubmissions(scope.row)"
            link
          >
            批改
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDeleteHomework(scope.row)"
            link
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="total > 0"
      class="pagination"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加/编辑作业对话框 -->
    <el-dialog
      :title="dialogType === 'create' ? '新建作业' : '编辑作业'"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form 
        ref="homeworkFormRef" 
        :model="homeworkForm" 
        :rules="homeworkRules" 
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="homeworkForm.title" placeholder="请输入作业标题" />
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="homeworkForm.classId" placeholder="请选择班级">
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="homeworkForm.subjectId" placeholder="请选择学科">
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="homeworkForm.content"
            type="textarea"
            rows="6"
            placeholder="请输入作业内容"
          />
        </el-form-item>
        <el-form-item label="截止日期" prop="endTime">
          <el-date-picker
            v-model="homeworkForm.endTime"
            type="datetime"
            placeholder="选择截止日期时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHomeworkForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getHomeworkList, createHomework, updateHomework, deleteHomework } from '@/api/homework'
import { getClassList } from '@/api/class'
import { getSubjectList } from '@/api/subject'
import { useRouter } from 'vue-router'
import { formatDate } from '@/utils/date'

const router = useRouter()
const homeworkList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogType = ref('create')
const classList = ref([])
const subjectList = ref([])

// 表单相关
const homeworkFormRef = ref(null)
const homeworkForm = reactive({
  id: '',
  title: '',
  classId: '',
  subjectId: '',
  content: '',
  endTime: ''
})

const homeworkRules = {
  title: [{ required: true, message: '请输入作业标题', trigger: 'blur' }],
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  subjectId: [{ required: true, message: '请选择学科', trigger: 'change' }],
  content: [{ required: true, message: '请输入作业内容', trigger: 'blur' }],
  endTime: [{ required: true, message: '请选择截止日期', trigger: 'change' }]
}

// 获取作业列表
const fetchHomeworkList = async () => {
  loading.value = true
  try {
    const res = await getHomeworkList({
      page: currentPage.value,
      size: pageSize.value
    })
    homeworkList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取作业列表失败', error)
    ElMessage.error('获取作业列表失败')
  } finally {
    loading.value = false
  }
}

// 获取班级列表
const fetchClassList = async () => {
  try {
    const res = await getClassList()
    classList.value = res.data
  } catch (error) {
    console.error('获取班级列表失败', error)
  }
}

// 获取学科列表
const fetchSubjectList = async () => {
  try {
    const res = await getSubjectList()
    subjectList.value = res.data
  } catch (error) {
    console.error('获取学科列表失败', error)
  }
}

// 处理新建作业
const handleCreateHomework = () => {
  dialogType.value = 'create'
  resetHomeworkForm()
  dialogVisible.value = true
}

// 处理编辑作业
const handleEditHomework = (row) => {
  dialogType.value = 'edit'
  resetHomeworkForm()
  Object.assign(homeworkForm, row)
  dialogVisible.value = true
}

// 处理查看作业
const handleViewHomework = (row) => {
  router.push(`/teacher/homework-detail/${row.id}`)
}

// 处理批改作业
const handleCheckSubmissions = (row) => {
  router.push(`/teacher/homework-submissions/${row.id}`)
}

// 处理删除作业
const handleDeleteHomework = (row) => {
  ElMessageBox.confirm('确定要删除该作业吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteHomework(row.id)
      ElMessage.success('删除成功')
      fetchHomeworkList()
    } catch (error) {
      console.error('删除作业失败', error)
      ElMessage.error('删除作业失败')
    }
  }).catch(() => {})
}

// 提交作业表单
const submitHomeworkForm = async () => {
  if (!homeworkFormRef.value) return
  
  await homeworkFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'create') {
          await createHomework(homeworkForm)
          ElMessage.success('创建作业成功')
        } else {
          await updateHomework(homeworkForm.id, homeworkForm)
          ElMessage.success('更新作业成功')
        }
        dialogVisible.value = false
        fetchHomeworkList()
      } catch (error) {
        console.error('保存作业失败', error)
        ElMessage.error('保存作业失败')
      }
    }
  })
}

// 重置表单
const resetHomeworkForm = () => {
  if (homeworkFormRef.value) {
    homeworkFormRef.value.resetFields()
  }
  Object.assign(homeworkForm, {
    id: '',
    title: '',
    classId: '',
    subjectId: '',
    content: '',
    endTime: ''
  })
}

// 获取作业状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 未开始
    1: 'success', // 进行中
    2: 'danger'   // 已结束
  }
  return statusMap[status] || 'info'
}

// 获取作业状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已结束'
  }
  return statusMap[status] || '未知'
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchHomeworkList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchHomeworkList()
}

onMounted(() => {
  fetchHomeworkList()
  fetchClassList()
  fetchSubjectList()
})
</script>

<style scoped>
.homework-list-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style> 